package com.googlecode.openrtp.main;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.googlecode.openrtp.grizzly.RtpSessionFactory;
import com.googlecode.openrtp.spi.PayloadType;
import com.googlecode.openrtp.spi.RtpSession;
import com.googlecode.openrtp.spi.RtpSessionManager;
import com.googlecode.openrtp.spi.SessionKeys;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ServiceLoader;
import java.util.logging.ConsoleHandler;
import java.util.logging.LogManager;
import com.googlecode.openrtp.spi.server.Server;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Hello world!
 *
 */
public class Main {

    private static void initConfig() {
        try {
            LogManager.getLogManager().readConfiguration(Main.class.getResourceAsStream("/logging.properties"));
        }
        catch (IOException | SecurityException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Inject
    @Named("RTP")
    private Server rtpServer;
    
    @Inject
    @Named("RTCP")
    private Server rtcpServer;
    
    @Inject
    private RtpSessionManager sessionManager;

    public static void main(String[] args)  {
        initConfig();
        
        LogManager.getLogManager().getLogger("").addHandler(new ConsoleHandlerImpl());
        Main m = new Main();
        Guice.createInjector(ServiceLoader.load(AbstractModule.class)).injectMembers(m);
        m.rtcpServer.start();
        m.rtpServer.start();
        RtpSession session = m.sessionManager.create(new Random().nextLong());
        session.set(SessionKeys.RTP_PACKET_RATE, Long.valueOf(20));
        session.set(SessionKeys.RTP_PACKET_SIZE, Long.valueOf(160));
        session.set(SessionKeys.PAYLOAD_TYPE, PayloadType.AUDIO_VIDEO);
        try {
            session.connectRtp("127.0.0.1", 5500);
            FileSystem fileSystem = FileSystems.getDefault();
            session.appendToOutBuffer(Files.readAllBytes(fileSystem.getPath("/home/jocke/rtp-data/mpthreetest.mp3")));
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static class ConsoleHandlerImpl extends ConsoleHandler {
        
        
        @Override
        protected synchronized void setOutputStream(OutputStream outputStream) throws SecurityException {
            super.setOutputStream(System.out);
        }
        
        
    }
}
